package com.cx.dubbo.utils;

import java.lang.reflect.Method;

import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Service;

@Service
public class SpringContextHolder implements ApplicationContextAware {
    private static ApplicationContext applicationContext;

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        SpringContextHolder.applicationContext = applicationContext;
    }


    public static ApplicationContext getApplicationContext() {
        return applicationContext;
    }
    public static Object getBean(String beanName) {
        return applicationContext.getBean(beanName);
    }
    
    public static <T>T getBean(String beanName , Class<T>clazz) {
        return applicationContext.getBean(beanName , clazz);
    }
    
    /**
     * beanName：spring里的bean名称
     * methodName：要调度的方法
     * classes：该方法里的传参类型
     * arguments：参数值
     * */
    public static Object gotoMethodByReflect(String beanName,String methodName,Class[] classes,Object[] arguments) throws Exception {
    	Object object = applicationContext.getBean(beanName);
		Method m = object.getClass().getMethod(methodName, classes);
		return m.invoke(object , arguments);
    }
    
    /**
     * beanName：spring里的bean名称
     * methodName：要调度的方法
     * arguments：参数值
     * */
    public static Object gotoMethodByReflect(String beanName,String methodName,Object[] arguments) throws Exception {
    	Object object = applicationContext.getBean(beanName);
    	Method[] methods = object.getClass().getMethods();
    	for(Method m :methods){
    		if(methodName.equals(m.getName())){
    			return m.invoke(object, arguments);
    		}
    	}
		return null;
    }
}
